from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ
from rest_framework.generics import CreateAPIView

# Create your views here.
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializers


class OauthQQloginView(APIView):
    """
        构建qq登录跳转链接
    """

    def get(self, request):
        # 1、获取前端定义好的验证字符串数据
        state = request.query_params.get('next', None)

        # 2、判断前端是否传递验证字符串数据
        if not state:
            state = '/'

        # 3、创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        # 4、构建跳转连接
        login_url = qq.get_qq_url()

        # 5、返回跳转连接
        return Response({'login_url': login_url})


class OauthView(APIView):
    def get(self, request):
        # 1、获取code值
        code = request.query_params.get('code', None)

        # 2、判断code是否传递过来
        if not code:
            return Response({'errors': '缺少code值'}, status=400)

        # 3、通过code值获取access_token值
        state = '/'
        # 创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        access_token = qq.get_access_token(code)
        # 4、通过access_token值获取opendi值
        openid = qq.get_open_id(access_token)

        # 5、判断openid是否绑定过美多用户
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 6、未绑定，进入到绑定页面完成绑定

            tjs = TJS(settings.SECRET_KEY, 300)

            open_id = tjs.dumps({'openid': openid}).decode()

            return Response({'access_token': open_id})

        else:
            # 7、绑定过，则登录成功
            # 生成JWT-token值
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)  # 生成载荷部分
            token = jwt_encode_handler(payload)  # 生成token

            return Response(
                {
                    'token': token,
                    'username': user.username,
                    'user_id': user.id
                }
            )

    # def post(self,request):
    #
    #     # 绑定保存
    #     OAuthQQUser.objects.create(user=user,openid=openid)

    def post(self, request):
        # 1、获取前端数据
        data = request.data
        # 2、验证数据
        ser = OauthSerializers(data=data)
        ser.is_valid()
        print(ser.errors)
        # 3、绑定保存数据
        ser.save()
        # 4、返回结果
        return Response(ser.data)
